<template>
  <div>
    <AButton type="outline" status="normal" @click="openImportModal"> 导入 </AButton>
    <!-- 导入 -->
    <AModal
      v-model:visible="importDialogVisible"
      draggable
      title="导入"
      :mask-closable="false"
      :footer="false"
      @close="modalEvent('close')"
      @open="modalEvent('open')"
    >
      <ASpin :loading="loading" tip="上传中" class="w100">
        <AUpload
          :custom-request="customRequest"
          :show-file-list="false"
          :error="uploadError"
          :success="uploadSuccess"
          draggable
        >
          <template #upload-button>
            <div class="upload-card">
              <icon-plus />
              <div>拖入文件或者 <em>点击上传</em></div>
            </div>
          </template>
        </AUpload>
        <div v-if="fileTemp" class="ltmt-mt-12 ltmt-template ltmt-mb-10">
          <span>点击下载</span>
          <ALink :hoverable="false" @click="fileTemp()"> 文件模板</ALink>
        </div>
        <div v-if="importResp.successCount || importResp.failedCount" class="erp-row-item-center">
          <span>
            {{
              `文件上传成功，数据导入成功${importResp.successCount}条，失败${importResp.failedCount}条`
            }}
          </span>
          <ALink v-if="importResp.failedCount" :href="importResp.failedDataFileUrl">调整文件</ALink>
        </div>
      </ASpin>
    </AModal>
  </div>
</template>

<script lang="ts" setup>
import { Message, RequestOption } from '@arco-design/web-vue'
import router from '@renderer/router'
import { useUserStore } from '@renderer/store'
import { getToken } from '@renderer/utils/auth'

interface Props {
  [key: string]: any
  impUrl: string
  fileTemp?: () => void
  otherParam?: object
}

const props = withDefaults(defineProps<Props>(), {
  impUrl: ''
})
const emit = defineEmits(['EndCallBack'])
const userInfo = useUserStore().localUserInfo
const baseURL = 'http://47.122.115.90:8000/admin-api'
const importDialogVisible = ref(false)
const loading = ref(false)
const importResp = ref({
  failedCount: 0,
  failedDataFileUrl: '',
  importResult: 0,
  successCount: 0
})

const uploadSuccess = () => {
  Message.success('')
}
const uploadError = () => {
  Message.error('')
}

const customRequest = (option: RequestOption) => {
  loading.value = true
  const { onProgress, onError, onSuccess, fileItem } = option
  const xhr = new XMLHttpRequest()
  if (xhr.upload) {
    xhr.upload.onprogress = function (event) {
      let percent
      if (event.total > 0) {
        // 0 ~ 1
        percent = event.loaded / event.total
      }
      onProgress(percent, event)
    }
  }
  xhr.onerror = function error(e) {
    loading.value = false
    onError(e)
  }
  xhr.onload = function onload() {
    const res = JSON.parse(xhr.response)
    if (xhr.status < 200 || xhr.status >= 300) {
      Message.error(res.msg)
      loading.value = false
      return onError(xhr.responseText)
    }
    if (res.code !== '20000') {
      if (res.code === '401') {
        const currentRoute = router.currentRoute.value
        router.push({
          name: 'login',
          query: {
            ...router.currentRoute.value.query,
            redirect: currentRoute.name as string
          }
        })
      } else {
        Message.error({
          content: res.msg || 'Error',
          duration: 5 * 1000
        })
      }
      loading.value = false
      return onError(xhr.responseText)
    }
    loading.value = false
    importResp.value = JSON.parse(xhr.response).data
    Message.success(
      `文件上传成功，数据导入成功${importResp.value.successCount}条，失败${importResp.value.failedCount}条`
    )
    emit('EndCallBack')
    onSuccess(xhr.response)
  }

  const formData = new FormData()
  formData.append('file', fileItem.file!)
  if (props.otherParam) {
    for (const key in props.otherParam) {
      formData.append(key, props.otherParam[key])
    }
  }
  xhr.open('post', baseURL + props.impUrl, true)
  xhr.setRequestHeader('token', getToken()!)
  xhr.setRequestHeader('tenant-id', userInfo.tenantId)
  xhr.send(formData)

  return {
    abort() {
      xhr.abort()
    }
  }
}

const modalEvent = (type: string) => {
  switch (type) {
    case 'close':
      importResp.value = {
        failedCount: 0,
        failedDataFileUrl: '',
        importResult: 0,
        successCount: 0
      }
      break
    case 'open':
      console.log(1)
      break
    default:
      break
  }
}

const openImportModal = () => {
  importDialogVisible.value = true
}
</script>
<style scoped lang="less">
.upload-card {
  background-color: var(--color-fill-2);
  color: var(--color-text-1);
  border: 1px dashed var(--color-fill-4);
  height: 158px;
  width: 100%;
  border-radius: 2px;
  height: 158px;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>
